package com.example.yunkafka.Controller;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Properties;

/**
 * @author CHENTAIWEN
 * @create 2022/8/25 8:28
 */
@RestController
public class KafkaController {

    @Value("${spring.kafka.bootstrap-servers}")
    public String kafkaServer;
    @GetMapping("addAll")
    public void addAll() throws InterruptedException {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,kafkaServer);
        props.put(ProducerConfig.RETRIES_CONFIG,0);
        props.put(ProducerConfig.LINGER_MS_CONFIG,1); //发送延迟 1秒
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432);//管理的最大内存
        props.put(ProducerConfig.ACKS_CONFIG,"1");
        props.put(ProducerConfig.BATCH_SIZE_CONFIG,16384);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);
        //3.在my-topic主题下，发送消息
        for(int i = 0; i < 10; i++) {
//            Thread.sleep(1000);
//            主题，消息key，消息内容
            producer.send(new ProducerRecord<>("Syan", Integer.toString(i), new Date().toString()));
            System.out.println("消息"+ new Date());
        }
        //4.关闭
        producer.close();
    }
}
